package com.wlw.admin.openeye.ui.fragment

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.wlw.admin.openeye.R
import com.wlw.admin.openeye.base.BaseFragment
import com.wlw.admin.openeye.mvp.contract.FollowContract
import com.wlw.admin.openeye.mvp.model.bean.HomeBean
import com.wlw.admin.openeye.mvp.presenter.FollowPresenter
import com.wlw.admin.openeye.net.exception.ErrorStatus
import com.wlw.admin.openeye.showToast
import com.wlw.admin.openeye.ui.adapter.FollowAdapter
import kotlinx.android.synthetic.main.layout_recyclerview.*

class FollowFragment : BaseFragment(), FollowContract.View {

    private lateinit var itemList: ArrayList<HomeBean.Issue.Item>
    private val mPresenter by lazy {
        FollowPresenter()
    }
    private val mFollowAdapter by lazy {
        context?.let { FollowAdapter(it,itemList) }
    }
    private var loadingMore = false

    init {
        mPresenter.attachView(this)
    }

    companion object {
        fun getInstance() = FollowFragment()
    }

    override fun getLayoutId(): Int = R.layout.layout_recyclerview

    override fun lazyLoad() {
        mPresenter.requestFollowList()
    }

    override fun initView() {
        itemList = ArrayList()
        val linearLayoutManager = LinearLayoutManager(activity)
        mRecyclerView.layoutManager = linearLayoutManager
        mRecyclerView.adapter = mFollowAdapter
        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val itemCount = linearLayoutManager.itemCount
                val lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition()
                if (!loadingMore && lastVisibleItem == (itemCount - 1)) {
                    loadingMore = true
                    mPresenter.loadMoreData()
                }
            }
        })
        mLayoutStatusView = multipleStatusView
    }

    override fun setFollowInfo(issue: HomeBean.Issue) {
        loadingMore = false
        itemList = issue.itemList
        mFollowAdapter?.addData(itemList)
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR)
            multipleStatusView.showNoNetwork()
        else
            multipleStatusView.showError()
    }

    override fun showLoading() {
        multipleStatusView.showLoading()
    }

    override fun dismissLoading() {
        multipleStatusView.showContent()
    }

}